/**
 * Created by DevilsEyes on 2016/5/14.
 */
'use strict';

let $task = require('../db/task');

let TYPE = {
    checkFile: 1
};

let filter = (t)=> {
    return {
        _id: t._id,
        type: t.type,
        time: t.time,
        json: t.json
    }
};

module.exports = {

    type: TYPE,
    getType: (number)=> {

        for (let type in TYPE) {
            TYPE[type] === number;
            return type;
        }

    },

    regist: (type, time)=> {

        return new Promise((O, X)=> {
            if (TYPE[type] === undefined)return X({
                code: 9999,
                msg: '不存在的任务类型'
            });
            let Task_Entity = new $task({
                type: TYPE[type],
                time: time
            });
            Task_Entity.save((err, task)=> {
                O(filter(task));
            })
        });

    },

    removeById: (id)=> {
        return new Promise((O, X)=> {
            $task.remove({_id: id})
                .then(()=> {
                    O()
                })
        });
    },

    getAvaliable: ()=> {

        let now = new Date().getTime();

        return new Promise((O, X)=> {
            $task
                .where('time')
                .lte(now)
                .then((tasks)=> {
                    O(tasks.map((t)=>filter(t)));
                })
        });
    },

    getAll: ()=> {
        return new Promise((O, X)=> {
            $task
                .find({})
                .then((tasks)=> {
                    O(tasks.map((t)=>filter(t)));
                })
        });
    },

    clearAll: ()=> {
        return new Promise((O, X)=> {
            $task.remove({})
                .then(()=> {
                    O()
                })
        });
    }

};